package com.rzico.sbl.ui.manager

import com.amap.api.services.core.PoiItem
import com.jeremyliao.liveeventbus.LiveEventBus
import com.jeremyliao.liveeventbus.utils.observe
import com.lzg.extend.jackson.JsonUtil
import com.lzy.okgo.model.HttpMethod
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityPickupModifyBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.PickCategory
import com.rzico.sbl.model.PickData
import com.rzico.sbl.model.RegionBean
import com.rzico.sbl.other.showAreaDialog
import com.rzico.sbl.ui.member.MemberAdressAddActivity
import com.rzico.sbl.viewmodel.ShopViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.doubleValue
import com.xinnuo.common.other.NameLengthFilter
import com.xinnuo.common.helper.isTel
import com.xinnuo.common.helper.isVirtual
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.utils.clear
import com.xinnuo.common_ui.utils.showListDialog
import org.json.JSONObject

class PickupModifyActivity : BaseActivity(R.layout.activity_pickup_modify) {

    private val mBinding by lazy { ActivityPickupModifyBinding.bind(getRootView()) }

    private lateinit var mMode: String
    private val mCategoryList = arrayListOf<PickCategory>()
    private val mAreaList = arrayListOf<RegionBean>()
    private var mShopId = ""
    private var mAreaId = ""
    private var mAreaCode = ""
    private var mCategoryId = ""
    private var mLat = 0.0
    private var mLng = 0.0

    override fun getViewModel() = get<ShopViewModel>()

    override fun initData() {
        initTitle(title = intent.getExtra("title"))

        when (mMode) {
            "add" -> mBinding.shopSave.text = "确认添加"
            "edit" -> mShopId.notEmpty { getData() }
        }
    }

    override fun initListener() {
        mBinding.apply {
            mShopId = intent.getExtra("shopId")
            mMode = intent.getExtra("mode")
            shopName.filters = arrayOf(NameLengthFilter(20))

            // 省市区选择
            shopArea.oneClick {
                mAreaList
                    .isNotEmpty()
                    .conditionElse(
                        actionTrue = ::showBottomArea,
                        actionFalse = {
                            getViewModel()
                                .getAreaList {
                                    mAreaList.addItems(it)

                                    showBottomArea()
                                }
                        }
                    )
            }

            // 地图选点
            shopAreaMap.oneClick {
                startActivityEx<MemberAdressAddActivity>()
            }

            // 所属分类
            shopCategoryLl.oneClick {
                getCategories {
                    showCategoryDialog()
                }
            }

            shopSave.oneClick {
                when {
                    shopTitle.textTrim.isEmpty() -> {
                        showToast("请输入站点名称")
                        shopTitle.requestFocus()
                        return@oneClick
                    }

                    shopName.textTrim.isEmpty() -> {
                        showToast("请输入联系姓名")
                        shopName.requestFocus()
                        return@oneClick
                    }

                    shopPhone.textTrim.isEmpty() -> {
                        showToast("请输入联系电话")
                        shopPhone.requestFocus()
                        return@oneClick
                    }

                    shopArea.content.isEmpty() -> {
                        showToast("请选择所在地区")
                        return@oneClick
                    }

                    shopDetail.textTrim.isEmpty() -> {
                        showToast("请输入详细地址")
                        shopDetail.requestFocus()
                        return@oneClick
                    }

                    !shopPhone.content.isTel()
                            && !shopPhone.content.isVirtual() -> {
                        showToast("请输入正确的联系电话")
                        shopPhone.requestFocus()
                        return@oneClick
                    }
                }

                getViewModel()
                    .request(
                        requestUrl = if (mMode == "add") BaseUrl.mngPickAdd else BaseUrl.mngPickUpd,
                        isMultipart = true,
                        params = arrayOf(
                            "id" to mShopId,
                            "name" to shopTitle.textTrim,
                            "categoryId" to 1,
                            "linkman" to shopName.textTrim,
                            "telephone" to shopPhone.content,
                            "areaId" to mAreaId,
                            "areaCode" to mAreaCode,
                            "address" to shopDetail.textTrim,
                            "shopCategoryId" to mCategoryId,
                            "lat" to mLat,
                            "lng" to mLng
                        ),
                        onSuccess = { json ->
                            when (mMode) {
                                "add" -> showToast("添加站点成功！")
                                "edit" -> showToast("站点修改成功！")
                            }

                            // 刷新站点列表
                            JsonUtil.jsonToBean(
                                json,
                                PickData::class.java
                            )?.let {
                                when (mMode) {
                                    "add" -> it.extend = "add"
                                    "edit" -> it.extend = "update"
                                }

                                LiveEventBus
                                    .get("pickList")
                                    .post(it)
                            }

                            finishView()
                        }
                    )
            }

            LiveEventBus
                .get("adressAdd", PoiItem::class.java)
                .observe(getLifecycleOwner()) {
                    mLat = it.latLonPoint.latitude
                    mLng = it.latLonPoint.longitude
                    mAreaId = ""
                    mAreaCode = it.adCode

                    shopArea.text = "${it.provinceName} ${it.cityName} ${it.adName}"
                    shopDetail.setText(it.snippet + it.title)
                    shopDetail.setSelection(shopDetail.text.length)
                }

            observe<String>("pickCategory") { mCategoryList.clear() }
        }
    }

    private fun showCategoryDialog() {
        val items = arrayListOf("添加分类")

        showListDialog(
            title = "请选择分类",
            items = mCategoryList.mapTo(items) { it.name },
            listener = { index, hint ->
                when (index) {
                    0 -> startActivityEx<PickupCategoryActivity>()
                    else -> {
                        mCategoryId = mCategoryList[index - 1].id
                        mBinding.shopCategory.text = hint
                    }
                }
            }
        )
    }

    /**
     * 店铺分类
     */
    private fun getCategories(onNext: () -> Unit) {
        mCategoryList
            .isEmpty()
            .conditionElse(
                actionTrue = {
                    getViewModel()
                        .categoryList(
                            type = "dummy",
                            onSuccess = {
                                mCategoryList.clear()
                                mCategoryList.addItems(it)
                            },
                            onFinally = onNext
                        )
                },
                actionFalse = onNext
            )
    }

    /**
     * 省市区弹框
     */
    private fun showBottomArea() {
        showAreaDialog(
            title = "请选择地区",
            list = mAreaList,
            listener = { pname, cname, aname, _, _, adcode ->
                mBinding.apply {
                    mLat = 0.0
                    mLng = 0.0
                    mAreaId = ""
                    mAreaCode = adcode

                    shopArea.text = "$pname $cname $aname"
                    shopDetail.clear()
                }
            }
        )
    }

    /**
     * 店铺详情
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .request(
                requestUrl = BaseUrl.shopDet,
                requestMethod = HttpMethod.GET,
                params = arrayOf("shopId" to mShopId),
                onSuccess = {
                    val obj = JSONObject(it)

                    mBinding.apply {
                        mAreaId = obj.optNotNull("areaId")
                        mCategoryId = obj.optNotNull("shopCategoryId")
                        mLat = obj.optNotNull("lat").doubleValue
                        mLng = obj.optNotNull("lng").doubleValue

                        shopTitle.setText(obj.optNotNull("name"))
                        shopName.setText(obj.optNotNull("linkman"))
                        shopPhone.setText(obj.optNotNull("telephone"))
                        shopArea.text = obj.optNotNull("areaName")
                        shopDetail.setText(obj.optNotNull("address"))
                        shopCategory.text = obj.optNotNull("shopCategoryName")
                    }
                }
            )
    }

}